<?php


namespace app\admin\middleware;

use app\admin\service\Auth;
use DI\Annotation\Inject;
use support\annotation\NoNeedLogin;
use support\bootstrap\Container;
use support\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;

class CheckLogin implements MiddlewareInterface
{
    use GetAnnotaion;

    /**
     * @var Auth
     * @Inject()
     */
    protected $service = null;

    public function process($request, callable $next): Response
    {
        $res = $this->noNeedLogin($request);
        if ($res !== true) {
            return $res;
        }
        return $next($request);
    }

    protected function noNeedLogin(Request $request)
    {
        if ($request->controller) {
            $controller = Container::get($request->controller);
            // 判断当前访问方法是否在不需要登录列表中
            if (!$this->match($request, $controller->noNeedLogin) && !$this->getHasAnnotation($request, NoNeedLogin::class)) {
                // 没有登录 重定向
                if (!$this->service->isLogin()) {
                    return redirect($controller->noLoginRedirectUrl);
                }
            }

            if ($this->match($request, $controller->excludeLogined)) {
                if ($this->service->isLogin()) {
                    return redirect($controller->loginedRedirectUrl);
                }
            }
        }
        return true;
    }

    protected function match($request, $arr = [])
    {
        $arr = is_array($arr) ? $arr : implode(',', $arr);
        if (!$arr) {
            return false;
        }
        $arr = array_map('strtolower', $arr);
        // 是否存在
        if (in_array(strtolower($request->action), $arr) || in_array('*', $arr)) {
            return true;
        }
        return false;
    }
}
